<template>
  <ych-modal
    :fullscreen="false"
    :title="title"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :cancelText="$t('m.common.button.close')">

    <a-button-group style="margin-bottom: 8px;">
      <a-button icon="plus" @click="handleAdd">{{ $t('m.bpm.design.xin-zeng-shu-ju-zi-duan') }}</a-button>
    </a-button-group>
    <a-table
      size="small"
      bordered
      rowKey="id"
      :columns="columns"
      :pagination="false"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
      :dataSource="data">

      <template slot="key" slot-scope="text, record">
        <ych-editable-cell v-if="visible && record.type != '1'" :text="text"
                       @change="onCellChange(record.id, 'key', $event)"/>
        <span v-else>
          {{text}}
        </span>
      </template>
      <template slot="alias" slot-scope="text, record">
        <ych-editable-cell v-if="visible && record.type != '1'" :text="text"
                       @change="onCellChange(record.id, 'alias', $event)"/>
        <span v-else>
          {{text}}
        </span>
      </template>

      <template slot="customEditableTitle">
        <a-checkbox v-if="visible" @change="checkallEditable($event)">
          {{$t('m.eform.formDesign.label.ke-bian-ji')}}
        </a-checkbox>
      </template>
      <template slot="editable" slot-scope="text, record">
        <ych-editable-cell v-if="visible" :checkflg="!!text" type="checkbox" :allCheck="allCheck"
                       @change="onCellChange(record.id, 'editable', $event)"/>
      </template>
      <template slot="customRequiredTitle">
        <a-checkbox v-if="visible" @change="checkallRequired($event)">
          {{$t('m.bpm.design.required')}}
        </a-checkbox>
      </template>
      <template slot="required" slot-scope="text, record">
        <ych-editable-cell v-if="visible" :checkflg="!!text" type="checkbox" :allCheck="allCheckRequired"
                           @change="onCellChange(record.id, 'required', $event)"/>
      </template>

      <template slot="customHiddenTitle">
        <a-checkbox v-if="visible" @change="checkallHidden($event)">
          {{$t('m.bpm.design.hidden')}}
        </a-checkbox>
      </template>
      <template slot="hidden" slot-scope="text, record">
        <ych-editable-cell v-if="visible" :checkflg="!!text" type="checkbox" :allCheck="allCheckHidden"
                           @change="onCellChange(record.id, 'hidden', $event)"/>
      </template>

      <template slot="operation" slot-scope="text, record">
        <a @click="handleDel(record.id)" v-if="record.type != '1'">{{ $t('m.common.button.delete') }}</a>
      </template>
    </a-table>

  </ych-modal>
</template>

<script>

  import {getAction} from '@/api/manage';
  import YchConstant from "@/api/YchConstant";
  import {YchEditableCell} from '@yuncheng/ych-components'
  import LocaleUtil from "../../../../utils/LocaleUtil";

  export default {
    name: "FormModelSecDialog",
    components: {
      YchEditableCell
    },
    data() {
      return {
        title: this.$t('m.bpm.other.process_dialog'),
        visible: false,
        value: [],
        requiredValue: [],
        hiddenValue: [],
        data: [],
        models: [],
        formModels: [],
        selectedRowKeys: [],
        formCode: null,
        allCheck:false,
        allCheckRequired:false,
        allCheckHidden:false,
        columns: [{
          title:this.$t('m.common.label.number'),
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        }, {
          title: this.$t('m.bpm.design.shu-ju-zi-duan'),
          align: 'center',
          width: 180,
          dataIndex: 'key',
          scopedSlots: {customRender: 'key'}
        }, {
          title: this.$t('m.bpm.design.shu-ju-biao-qian'),
          align: 'center',
          width: 180,
          dataIndex: 'alias',
          scopedSlots: {customRender: 'alias'}
        }, {
          title: this.$t('m.bpm.design.variable_source'),
          align: 'center',
          width: 80,
          dataIndex: 'type',
          customRender: (text) => {
            if (text == '1') {
              return LocaleUtil.getLocale('m.bpm.design.variable_source_eform');
            } else {
              return LocaleUtil.getLocale('m.bpm.design.variable_srouce_custom');
            }
          }
        }, {
          align: 'center',
          width: 120,
          dataIndex: 'editable',
          scopedSlots: {customRender: 'editable'},
          slots: { title: 'customEditableTitle' },
        }, {
          align: 'center',
          width: 120,
          dataIndex: 'required',
          scopedSlots: {customRender: 'required'},
          slots: { title: 'customRequiredTitle' },
        }, {
          align: 'center',
          width: 120,
          dataIndex: 'hidden',
          scopedSlots: {customRender: 'hidden'},
          slots: { title: 'customHiddenTitle' },
        }, {
          title: this.$t('m.common.label.operate'),
          dataIndex: 'action',
          scopedSlots: {customRender: 'operation'},
          align: 'center',
          width: 120
        }],
        url: {
          getFormModelList: YchConstant.PREFIX_BPM + "/bpm-back/processDefRest/getFormModelList/v1",
        }
      }
    },
    methods: {
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
      },
      open(value, formCode, models, requiredValue, hiddenValue) {
        this.value = value ? JSON.parse(value) : [];
        this.requiredValue = requiredValue ? JSON.parse(requiredValue) : [];
        this.hiddenValue = hiddenValue ? JSON.parse(hiddenValue) : [];

        this.models = models ? JSON.parse(models) : [];
        this.data = [...this.formModels, ...this.models];
        this.initEditable();

        this.formCode = formCode;

        this.visible = true;
      },
      handleOk() {
        const models = this.data.filter(item => item.type != '1' && item.key);
        const value = [];
        const alias = [];
        this.data.filter(item => item.editable && item.key).forEach(vo => {
          value.push(vo.key);
          alias.push(vo.alias || vo.key);
        });

        let showMessage = false;
        const requiredValue = [];
        const requiredAlias = [];
        this.data.filter(item => item.required && item.key).forEach(vo => {
          if (vo.editable) {
            requiredValue.push(vo.key);
            requiredAlias.push(vo.alias || vo.key);
          } else {
            showMessage = true;
          }
        });
        if (showMessage) {
          this.messageUtil.warning(this.$t('m.bpm.design.auto_del_fields_msg'))
        }

        const hiddenValue = [];
        const hiddenAlias = [];
        this.data.filter(item => item.hidden && item.key).forEach(vo => {
          hiddenValue.push(vo.key);
          hiddenAlias.push(vo.alias || vo.key);
        });

        this.$emit('selectFinished',
          this.$t('m.bpm.design.ke-bian-ji-zi-duan') + JSON.stringify(alias),
          value.length > 0 ? JSON.stringify(value) : null,
          JSON.stringify(models),
          this.$t('m.bpm.design.bi-tian-zi-duan') + JSON.stringify(requiredAlias),
          requiredValue.length > 0 ? JSON.stringify(requiredValue) : null,
          this.$t('m.bpm.design.yin-cang-zi-duan') + JSON.stringify(hiddenAlias),
          hiddenValue.length > 0 ? JSON.stringify(hiddenValue) : null);
        this.handleCancel();
      },
      handleCancel() {
        this.visible = false;
      },
      onCellChange(key, dataIndex, value) {
        const data = [...this.data];
        const target = data.find(item => item.id === key);
        if (target) {
          target[dataIndex] = value;
          this.data = data;
        }
      },
      handleAdd() {
        const {data} = this;
        const newData = {
          id: "" + Math.random(),
          key: "",
          alias: "",
          type: "2"
        };
        this.data = [...data, newData];
      },
      checkallEditable(event){
        if (event.target.checked){
          this.allCheck = true
        }else{
          this.allCheck = false
        }
      },
      checkallRequired(event){
        if(event.target.checked){
          this.allCheckRequired = true
        }else{
          this.allCheckRequired = false
        }
      },
      checkallHidden(event){
        if(event.target.checked){
          this.allCheckHidden = true
        }else{
          this.allCheckHidden = false
        }
      },
      handleDel(id) {
        const data = [...this.data];
        this.data = data.filter(item => item.id !== id);
      },
      initEditable() {
        this.data.forEach(vo => {
          vo["editable"] = this.value.indexOf(vo.key) != -1
          vo["required"] = this.requiredValue.indexOf(vo.key) != -1
          vo["hidden"] = this.hiddenValue.indexOf(vo.key) != -1
        });
      }
    },
    watch: {
      formCode: {
        handler(val) {
          if (val) {
            getAction(this.url.getFormModelList, {formCode: val}).then((res) => {
              if (res.success) {
                this.formModels = res.result;
                this.formModels.forEach(item => {
                  item.alias = LocaleUtil.getLocale(item.alias)
                })
                this.data = [...this.formModels, ...this.models];
                this.initEditable();
              } else {
                this.messageUtil.warning(res.message);
              }
            }).finally(() => {
            });
          } else {
            this.formModels = [];
            this.data = [...this.formModels, ...this.models];
            this.initEditable();
          }
        },
        immediate: true
      }
    }
  }
</script>
